#!/usr/bin/env python
# -*- coding:utf8 -*-
# uncompyle6 version 2.15.1
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.10 (default, Jul  1 2017, 13:36:56) 
# [GCC 4.4.6 20110731 (Red Hat 4.4.6-4)]
# Embedded file name: ./esb/components/generic/apis/cmsi/send_weixin.py
# Compiled at: 2017-11-16 15:44:28
"""
Copyright © 2012-2017 Tencent BlueKing. All Rights Reserved. 蓝鲸智云 版权所有
"""
import datetime, base64
from django import forms
from components.component import Component, SetupConfMixin
from common.forms import BaseComponentForm, ListField, TypeCheckField, DefaultBooleanField
from .toolkit import configs, tools

class SendWeixin(Component, SetupConfMixin):
    """
    apiLabel 发送微信消息
    apiMethod POST
    
    ### 功能描述
    
    发送微信消息，支持微信公众号消息，及微信企业号消息
    
    ### 请求参数
    
    {{ common_args_desc }}
    
    #### 接口参数
    
    | 字段               |  类型      | 必选   |  描述      |
    |--------------------|------------|--------|------------|
    | receiver           |  string    | 否     | 微信接收者，包含绑定在指定公众号上的微信用户的 openid 或 企业号上的微信用户的用户ID，多个以逗号分隔 |
    | receiver__username |  string    | 否     | 微信接收者，包含用户名，用户需在蓝鲸平台注册，多个以逗号分隔，若receiver、receiver__username同时存在，以receiver为准 |
    | data               |  dict      | 是     | 消息内容 |
    
    #### data 参数包含内容
    
    | 字段               |  类型      | 必选   |  描述      |
    |--------------------|------------|--------|------------|
    | heading            |  string    | 是     | 通知头部文字 |
    | message            |  string    | 是     | 通知文字 |
    | date               |  string    | 否     | 通知发送时间，默认为当前时间 "YYYY-mm-dd HH:MM" |
    | remark             |  string    | 否     | 通知尾部文字 |
    | is_message_base64  |  bool      | 否     | 通知文字message是否base64编码，默认False，不编码，若编码请使用base64.b64encode方法 |
    
    ### 请求参数示例
    
    ```python
    {
        "app_code": "esb_test",
        "app_secret": "xxx",
        "bk_token": "xxx",
        "receiver": "xxx",
        "data": {
            "heading": "蓝鲸平台通知",
            "message": "This 是 a test.",
            "date": "2017-02-22 15:36",
            "remark": "zhen 是一个测试！"
        }
    }
    ```
    
    ### 返回结果示例
    
    ```python
    {
        "result": true,
        "code": "00",
        "message": "微信消息发送成功。",
    }
    ```
    """
    sys_name = configs.SYSTEM_NAME
    contact_way = 'wx_userid'

    class Form(BaseComponentForm):
        receiver = ListField(label=u'微信接收人', required=False)
        receiver__username = ListField(label=u'微信接收人', required=False)
        data = TypeCheckField(label=u'消息数据', promise_type=dict, required=True)

        def clean(self):
            data = self.cleaned_data
            if not (data['receiver'] or data['receiver__username']):
                raise forms.ValidationError(u'微信接收人[receiver、receiver__username]不能同时为空。')
            if data['receiver']:
                data['receiver__username'] = None
            return {'receiver': data['receiver'],
               'receiver__username': data['receiver__username'],
               'data': SendWeixin.DataForm(data['data']).get_cleaned_data_or_error()
               }

    class DataForm(BaseComponentForm):
        heading = forms.CharField(label=u'通知头部文字', required=True)
        message = forms.CharField(label=u'通知文字', required=True)
        date = forms.CharField(label=u'通知发送时间', required=False)
        remark = forms.CharField(label=u'通知尾部文字', required=False)
        is_message_base64 = DefaultBooleanField(label=u'通知文字是否base64编码', default=False, required=False)

        def decode_message(self, message, is_message_base64):
            if is_message_base64:
                try:
                    message = base64.b64decode(message)
                except:
                    pass

            return message

        def clean(self):
            data = self.cleaned_data
            data.update({'date': data.get('date') or datetime.datetime.now().strftime('%Y-%m-%d %H:%M'),
               'message': self.decode_message(data['message'], data['is_message_base64'])
               })
            return data

    def get_mp_msg_data(self, data):
        return {'first': {'value': data['heading']
                     },
           'keyword1': {'value': data['message']
                        },
           'keyword2': {'value': data['date']
                        },
           'remark': {'value': data.get('remark', '')
                      }
           }

    def get_qy_msg_content(self, data):
        new_data = [
         data['heading'],
         u'消息内容：%s' % data['message'].decode('utf-8') if isinstance(data['message'], str) else data['message'],
         u'发送时间：%s' % data['date']]
        if data.get('remark'):
            new_data.append(data['remark'])
        return ('
').join(new_data)

    def handle(self):
        self.wx_type = getattr(self, 'wx_type', '') or getattr(configs, 'wx_type', '')
        self.wx_app_id = getattr(self, 'wx_app_id', '') or getattr(configs, 'wx_app_id', '')
        self.wx_secret = getattr(self, 'wx_secret', '') or getattr(configs, 'wx_secret', '')
        self.wx_template_id = getattr(self, 'wx_template_id', '') or getattr(configs, 'wx_template_id', '')
        self.wx_qy_corpid = getattr(self, 'wx_qy_corpid', '') or getattr(configs, 'wx_qy_corpid', '')
        self.wx_qy_corpsecret = getattr(self, 'wx_qy_corpsecret', '') or getattr(configs, 'wx_qy_corpsecret', '')
        self.wx_qy_agentid = getattr(self, 'wx_qy_agentid', '') or getattr(configs, 'wx_qy_agentid', '')
        data = self.form_data
        if data['receiver__username']:
            user_data = tools.get_receiver_with_username(receiver__username=data['receiver__username'], contact_way=self.contact_way)
            data.update(user_data)
        if self.wx_type == 'mp':
            data.update({'appid': self.wx_app_id,
               'secret': self.wx_secret,
               'template_id': self.wx_template_id,
               'url': self.request.kwargs.get('url', ''),
               'touser': data['receiver'],
               'data': self.get_mp_msg_data(data['data'])
               })
            result = self.invoke_other('generic.weixin_mp.send_msg_with_tpl', kwargs=data)
        else:
            if self.wx_type in ('qy', 'qywx'):
                data.update({'corpid': self.wx_qy_corpid,
                   'corpsecret': self.wx_qy_corpsecret,
                   'agentid': self.wx_qy_agentid,
                   'touser': data['receiver'],
                   'content': self.get_qy_msg_content(data['data'])
                   })
                result = self.invoke_other('generic.weixin_qy.send_message', kwargs=data)
            else:
                result = {'result': False,'message': u'不支持的微信类型 [wx_type=%s]' % self.wx_type}
        if result['result'] and data.get('_extra_user_error_msg'):
            result = {'result': False,'message': u'部分用户微信发送失败。%s' % data['_extra_user_error_msg']
               }
        self.response.payload = result
